<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/1/4
 * Time: 14:32
 */
namespace Home\Controller;

use Admin\Model\AssayClassModel;
use Admin\Model\DoctorInfoModel;
use Admin\Model\DoctorModel;
use Admin\Model\DoctorPatientRelativeModel;
use Admin\Model\FellowupstopInfoModel;
use Admin\Model\HealthRecordModel;
use Admin\Model\LinkModel;
use Admin\Model\PatientInfoModel;
use app\admin\controller\Index;
use Base\Controller\BaseHomeController;
use Library\BmobSms;
use Library\Chart;
use Think\Controller;
use Library\UploadFile;
use Think\Verify;

class DoctorInfoController extends BaseHomeController
{
    protected $model;
    protected $upload;
    public function __construct()
    {
        parent::__construct(false,true,array(
            'input_name' => 'certCover',//文本框name
            'save_path' => 'certCover',//保存路径
            'data_field' => 'certCover'//数据库字段
        ));
        $this->model = new DoctorInfoModel();
        $this->RelativeModel=new  DoctorPatientRelativeModel();
    }

        /**
         * @return bool
         * 根据栏目判断进行跳转
         */
        public  function index(){
            if(!I('genre')){
               $_REQUEST['genre']=1;
            }
            $this->assign('realname',session('name'));
            $where['doctorid']=session('userId');
                switch(I('genre'))
                {
                   case 1:
                       $where['relationtype']=array('in','0,1,2,4');
                       $data =$this->RelativeModel->pageToView(15, true,$where);
                       $this->assign("page", $data['page']);
                       $this->assign("patientlist", $data['list']);
                       $this->display();
                 break;
                     case 2:
                      $type=I('type');
                     if ($type==2){
                          $where['relationtype']=array('in','0,1,2,4');
                      }else{
                          $where['relationtype']=$type;
                      }
                       $datas= $this->RelativeModel->pageToView(7,true,$where);
                       $this->assign("page", $datas['page']);
                       $this->assign("list", $datas['list']);
//                   dump($datas);
                      $this->display('patientList');
                  break;
                default:
//                    $where['relationtype']=1;
//                    $data =$this->RelativeModel->pageToView(15, true,$where);
//                    $this->assign("page", $data['page']);
//                    $this->assign("patientlist", $data['list']);
                    $this->display();
//                    $this->success(U('index',array('genre'=>1)));
                      return false;
               break;
             }
        }
    /**
     * 用户注册
     */
    public  function reg()
    {
        $BmobSms=new BmobSms();
    if (!empty($_POST)) {
        if( $_REQUEST['phone'] && $_REQUEST['messages']);
        try{$result =$BmobSms->verifySmsCode($_REQUEST['phone'],$_REQUEST['messsagecode']);}
        catch (\Exception $exception){
            $this->error('验证码不正确，请检查您的验证码');
        }
        if($result->msg=="ok"){
            $data = $this->model->create();
            if (!$data) {
                $this->error($this->model->getError());
            } else {
                if ($this->upload) {
                    $input_name = $this->uploadConfig['input_name'];
                    $save_path = $this->uploadConfig['save_path'];
                    $data_field = $this->uploadConfig['data_field'];
                    if ($_FILES[$input_name]) {
                        $up = new UploadFile();
                        $info = $up->upFile($save_path, array('jpg', 'png', 'jpeg', 'gif'));
                        $data[$data_field] = $info[$input_name]['savepath'] . $info[$input_name]['savename'];
                    }
                    $data=$this->addAfter($data);
                    $add = $this->model->add($data);
                    $this->editdata($add);
                    if ($add) {
                        $this->success('注册成功',U('Index/login'));
                    }else{
                        $this->error('注册失败，请重新注册');
                    }
                }
            }
        }else{
            $this->error('验证码不正确，请检查您的验证码');
         }
       }
    }
      protected  function  addAfter($data)
        {
            $data['passwd']=md5(C('md5s').$data['passwd']);
            return $data;
        }
   protected  function editdata($add){
       $Chart=new Chart();
       $name='web-'.'doctor'.$add;
       $pwd='a123456';
       $Chart->registerUser($name,$pwd);
       $save['id']=$add;
       $save['bmob_username']=$name;
       $save['bmob_password']=$pwd;
       $this->model->save($save);
   }

    /**
     * 用户登陆
     */
    public function login()
    {
        if($_POST){
            $map['phone'] = $_POST['phone'];
            $map['passwd'] = md5(C('md5s').$_POST['passwd']);
            if (!$this->checkVerify(I('post.code'))) {
                $data['status']=-1;
                $data['msg']="验证码错误";
                echo json_encode($data);
            } else {
                $result = $this->model->where($map)->find();
                if($result){
                    if($result['status']==1){
                        session('userId',$result['id']);
                        session('name',$result['realname']);
                        $data['status']=1;
                        $data['msg']="登录成功";
                        $this->ajaxReturn($data);
                    }elseif ($result['status']==2){
                        $data['status']=2;
                        $data['msg']="审核未通过，请重新补全您的信息";
                        $this->ajaxReturn($data);
                    }elseif ($result['status']==3){
                        $data['status']=3;
                        $data['msg']="您的信息正在审核中，请耐心等待......";
                        $this->ajaxReturn($data);
                    }else{
                        $data['status']=-3;
                        $data['msg']="用户已经被删除，请重新注册新用户";
                        $this->ajaxReturn($data);
                    }
                }else{
                    $data['status']=-2;
                    $data['msg']="账号或密码错误";
                    $this->ajaxReturn($data);
                }
            }
        }else{
            $data['status']=-4;
            $data['msg']="请正确使用登录方式登录";
            $this->ajaxReturn($data);
        }
    }
    /**
     * 验证码是否正确
     * @param $code
     * @param string $id
     * @return bool
     */
    function checkVerify($code, $id = '')
    {
        $verify = new Verify();
        return $verify->check($code, $id);
    }
    /**
     * 重置密码
     */
    public  function  restpassword(){
        $BmobSms =new  BmobSms();
        $messages=$_REQUEST['messages'];
        $phone = $_REQUEST['phone'];
        try{
            $result =$BmobSms->verifySmsCode($phone,$messages);
        }catch (\Exception $exception){
            $data['msg']='验证码时效过期或多次使用验证码';
            $this->ajaxReturn($data);
        }
        if($result->msg=="ok"){
            $res=$this->model->where(array('phone'=>$phone))->find();
            if($res){
                $pwd=md5(C('md5s').I('post.passwd'));
                $this->model->where('id=' . $res['id'])->setField('passwd',$pwd );
               $data['status']=1;
                $data['msg']='密码重置成功';
               $this->ajaxReturn($data);
            }
        }else{
              $data['status']=-1;
              $data['msg']='验证码时效过期或多次使用验证码';
             $this->ajaxReturn($data);
        }
    }
    /**
     * 个人中心
     */
    public function info(){

        $where['id']=session('userId');
        $where['status']=1;
        $data= $this->model->relation(true)->where($where)->find();
        $this->assign('info',$data);
        $this->display();
    }
    /**
     * 编辑医生信息
     */
    public function edit()
    {
        if(empty($_POST['phone']) || empty($_POST['email'])){
            $this->model->validate(false);
        }
        $data = $this->model->create();
        if (!$data) {
            $this->error($this->model->getError());
        } else {
            if ($data['pwd'] == '') unset($data['pwd']);
            $result = $this->model->save($data);
            if ($result) {
                $this->success('编辑成功',U('Doctor/info'));
            }else{
            }
        }
    }
    /**
     * @param $data
     * @param $isEdit
     * @return mixed
     */
    function upDoctorImg($data,$isEdit){
        if ($this->upload & $_FILES) {
            $input_name = $this->uploadConfig['input_name'];
            $save_path = $this->uploadConfig['save_path'];
            $data_field = $this->uploadConfig['data_field'];
            $up = new UploadFile();
            $info = $up->upDifferentImg('cover');
            if ($isEdit){
                $data = $this->model->find($data['id']);
            }
            if ($_FILES[$input_name]) {
                if ($data[$data_field]) {
                    //删除
                    $upConfig = C('UPLOADS');
                    removeFile($upConfig['PATH'] . '/' . $data[$data_field]);
                }
                $data[$data_field] = $info[$input_name][$input_name]['savepath'] . $info[$input_name][$input_name]['savename'];
            }
            //上传资格证
            $input_name = 'certification';
            if ($_FILES[$input_name]) {
                $data_field = 'certification';
                if ($data[$data_field]) {
                    //删除
                    $upConfig = C('UPLOADS');
                    removeFile($upConfig['PATH'] . '/' . $data[$data_field]);
                }
//                    $info = $up->upFile($save_path, array('jpg', 'png', 'jpeg', 'gif'));
                $data[$input_name] = $info[$input_name][$input_name]['savepath'] . $info[$input_name][$input_name]['savename'];
            }
        }
        return $data;
    }

    /**
     * @param $type
     * @param $patient
     * $type为类型,1为拒绝，通过；
     * $patient为患者ID；
     */
    public  function revieweds(){
        $where['patientid']=I('patient');
        $where['doctorid']=session('userId');
        $type=I('type');
        $error['status']=1;
        $error['status']='请检查您的参数!';
        if(!$type)$this->ajaxReturn($error);
        $data['relationtype']=$type;
        $res=$this->RelativeModel->where($where)->save($data);
        if($res){
            $result['status']=1;
            if($type==22){
                $result['msg']="该患者已被你拒绝!";
            }else if($type==2){
                $result['msg']="该患者成功成为您的病人！";
            }else if($type==4){
                $result['msg']="该患者已被您成功设为特别关注！";
            }else if($type==3){
                $result['msg']="该患者已被您成功删除!";
            }
        }else{
            $result['status']=-1;
        }
          $this->ajaxReturn($result);
    }
    /**
     * 聊天界面
     */
    public  function chatview(){
         $patientid=I('patientid');
         $doctorid=session('userId');
         $PatientInfoModel=new PatientInfoModel();
         $patientinfo=$PatientInfoModel->find($patientid);
         $doctorinfo= $this->model->find($doctorid);
         $this->assign('patientinfo',$patientinfo);
         $this->assign('doctorinfo',$doctorinfo);
         $this->display();
    }
    /**
     *
     *随访终止
     */
    public  function  fellowupStop(){
          $FellowupstopInfoModel=new FellowupstopInfoModel();
           $DoctorPatientRelativeModel =new DoctorPatientRelativeModel();
          $data=$FellowupstopInfoModel->create();
          $data['doctorid']=session('userId');
          $res=$FellowupstopInfoModel->add($data);
          if($res){
          $where['patientid']=$data['userid'];
          $where['doctorid']=session('userId');
          $wheres['relationtype']=30;
          $DoctorPatientRelativeModel->where($where)->save($wheres);
          $datas['status']=1;
          $datas['msg']='信息提交成功!';
          }else{
              $datas['msg']='信息提交失败!';
          }
           echo json_encode($datas);
    }
}